<script>
  layui.use(["element", "layer", "jquery"], function () {
    var element = layui.element,
      layer = layui.layer,
      $ = layui.jquery;
    $.getJSON('<{caUrl("adminmenu","index")}>&list_json', {}, function (res) {
      if (res.data == undefined) return;
      var data = res.data;
      //console.log("data: " + data);
      var liStr = "";
      for (var i = 0; i < data.length; i++) {
        // 判断是否存在子菜单,支持无限级
        if (data[i].children != null && data[i].children.length > 0) {
          liStr +=
            '<li class="layui-nav-item layui-nav-itemed"><a class="" href="javascript:;"><i class="layui-icon ' +
            data[i].ico +
            '"></i> ' +
            data[i].name +
            "</a>\n" +
            '<dl class="layui-nav-child">\n';
          // 遍历获取子菜单
          for (var k = 0; k < data[i].children.length; k++) {
            liStr += getChild(data[i].children[k], 0);
          }
          liStr += "</dl></li>";
        } else {
          liStr +=
            '<li class="layui-nav-item"><a class="" href="javascript:;" onclick="loadMain(\'<{caUrl("' +
            data[i].controller +
            '","' +
            data[i].action +
            '")}>&menuname=' +
            data[i].name +
            '\')"><i class="layui-icon ' +
            data[i].ico +
            '"></i> ' +
            data[i].name +
            "</a></li>";
        }
      }
      //console.log(">>>> "+liStr);
      $("#leftMenu").html(
        '<ul class="layui-nav layui-nav-tree"  id="leftContent" lay-filter="">\n' +
          liStr +
          "</ul>"
      );
      element.init();
    });
  });
  var menuCell = 5;
  // 递归生成子菜单
  function getChild(subMenu, num) {
    num++;
    var subStr = "";
    if (subMenu.children != null && subMenu.children.length > 0) {
      subStr +=
        '<dd><ul><li class="layui-nav-item" ><a style="margin-Left:' +
        num * menuCell +
        'px" class="" href="javascript:;"><i class=\'layui-icon\' ' +
        subMenu.ico +
        "></i> " +
        subMenu.name +
        "</a>" +
        '<dl class="layui-nav-child">\n';
      for (var j = 0; j < subMenu.children.length; j++) {
        subStr += getChild(subMenu.children[j], num);
      }
      subStr += "</dl></li></ul></dd>";
    } else {
      subStr +=
        '<dd><a style="margin-Left:' +
        num * menuCell +
        'px" href="javascript:;" onclick="loadMain(\'<{caUrl("' +
        subMenu.controller +
        '","' +
        subMenu.action +
        '")}>&menuname=' +
        subMenu.name +
        '\')"><i class="layui-icon ' +
        subMenu.ico +
        '"></i> ' +
        subMenu.name +
        "</a></dd>";
    }
    return subStr;
  }
</script>
